<script setup>
import { PlusOutlined, SearchOutlined, } from '@ant-design/icons-vue';
import axios from "axios";
import { message } from "ant-design-vue";

//搜索条件
const formRef = ref();
const searchForm = reactive( {
  title : '', //标签名
  state : '', //状态
  create_time : [], //时间搜索
  orderField : '', //排序字段
  order : '',//排序顺序 asc|desc
} );
const stateOptions = ref( [
  { label : '全部', value : '' },
  { label : '启用', value : 1 },
  { label : '禁用', value : 0 },
] );
const typeOptions = ref( [
  { label : '普通通知', value : 1 },
  { label : '平台公告', value : 2 },
  { label : '系统通知', value : 3 },
] );
const userGroup = ref( [] );
const userGroupOptions = ref( [
  { label : '普通用户', value : 1 },
  { label : '测试用户', value : 2 },
  { label : '付费用户', value : 3 },
  { label : 'VIP用户', value : 4 },
] );
const onFinish = values => getList( values );
const onChangeDatePicker = ( date, dateString ) => {
  searchForm.create_time = dateString;
};
// TODO: 添加模态框
const formModalRef = ref();
const formData = reactive( {
  type : 1,
  title : '',
  keywords : '',
  content : '',
  state : true,
} );
const open = ref( false );
const showModal = ( id ) => {
  open.value = true;
  if ( id > 0 ) {
    axios.get( '/api/notice-info?id=' + id ).then( res => {
      if ( res.data.code !== 200 ) {
        message.error( res.data.msg );
        return false;
      } else {
        formData.value = res.data.data;
      }
    } ).catch( err => {
      console.log( err );
      message.error( '请求失败' );
    } )
  }
}
const handleOk = () => {
  axios.post( '/api/tags-create', formData ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg, 2, () => {
        formModalRef.value.resetFields();
        data.value.unshift( res.data.data );
        open.value = false;
        pagination.total++;
      } );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
};

//表格的表头
const columns = [
  { title : 'id', dataIndex : 'id', key : 'id', sorter : true, },
  { title : '标题', dataIndex : 'title', key : 'title', },
  { title : '关键字', dataIndex : 'keywords', key : 'keywords', },
  { title : '类型', dataIndex : 'type', key : 'type', },
  { title : '状态', dataIndex : 'state', key : 'state', },
  { title : '已读次数', dataIndex : 'read_num', key : 'read_num', },
  { title : '添加时间', dataIndex : 'create_time', key : 'create_time', sorter : true, },
  { title : '操作', key : 'action', },
];
//分页器
const pagination = reactive( {
  current : 1,
  pageSize : 10,
  total : 0,
  showSizeChanger : true,
  showTotal : function ( total ) {
    return `共${ total }条`;
  },
  onShowSizeChange : ( current, pageSize ) => {
    pagination.current = current;
    pagination.pageSize = pageSize;
    getList( searchForm );
  },
  onChange : ( page ) => {
    pagination.current = page;
    getList( searchForm );
  },
} );
// 获取列表
const data = ref();
const getList = ( values, filter, sorter ) => {
  if ( sorter !== undefined ) {
    if ( sorter.order === 'ascend' ) {
      searchForm.orderField = sorter.field;
      searchForm.order = 'asc';
    } else if ( sorter.order === 'descend' ) {
      searchForm.orderField = sorter.field;
      searchForm.order = 'desc';
    } else {
      searchForm.orderField = '';
      searchForm.order = '';
    }
  }
  let params = {
    page : pagination.current,
    pageSize : pagination.pageSize,
    title : searchForm.title,
    orderField : searchForm.orderField,
    order : searchForm.order,
    ...values,
  };
  axios.get( '/api/notice-manage-list', { params : params } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      data.value = res.data.data.list.map( item => {
        item.key = item.id;//批量选择时需设置key
        item.state = !!item.state;
        return item;
      } );
      pagination.total = res.data.data.total;
      pagination.current = parseInt( res.data.data.page );
      pagination.pageSize = parseInt( res.data.data.pageSize );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
}

// 修改标签状态
const handleChangeState = ( $event, id ) => {
  console.log( $event );
  let value = $event ? 1 : 0;
  axios.post( '/api/notice-manage-edit',
      { id : id, state : value, }
  ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg );
    }
  } ).catch( err => {
    console.log( err );
    message.error( '请求失败' );
  } );
}

// 删除标签
const handleDelete = ( id ) => {
  axios.post( '/api/tags-delete', { id : id } ).then( res => {
    if ( res.data.code !== 200 ) {
      message.error( res.data.msg );
    } else {
      message.success( res.data.msg, 1, () => {
        data.value = data.value.filter( item => item.id !== id );
        pagination.total--;
      } );
    }
  } ).catch( err => {
    console.log( err );
  } );
}

// 页面加载时调用
onMounted( () => {
  getList( searchForm );
} );
</script>

<template>
  <!-- 消息模态框 -->
  <template>
    <a-modal v-model:open="open" title="添加通知" ok-text="确定" cancel-text="取消" @ok="handleOk">
      <a-form name="addModal" ref="formModalRef" :model="formData" v-bind="{labelCol: {span: 4},wrapperCol: {span: 20}}">
        <a-form-item label="通知标题" name="title" :rules="[{ required: true, message: '请输入通知标题' }]" required>
          <a-input v-model:value="formData.title" placeholder="请填写标题" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="关键字" name="keywords" :rules="[{ required: true, message: '请输入关键字' }]" required>
          <a-input v-model:value="formData.keywords" placeholder="请填写标题" autocomplete="off"></a-input>
        </a-form-item>
        <a-form-item label="通知内容" name="content" :rules="[{ required: true, message: '请输入通知内容' }]" required>
          <a-textarea v-model:value="formData.content" :rows="4" placeholder="请输入内容" autocomplete="off"></a-textarea>
        </a-form-item>
        <a-form-item label="通知类型" name="type">
          <a-select v-model:value="formData.type" placeholder="请选择类型" :options="typeOptions"></a-select>
        </a-form-item>
        <a-form-item label="通知状态" name="state">
          <a-switch v-model:checked="formData.state" checked-children="启用" un-checked-children="禁用" v-remove-aria-hidden/>
        </a-form-item>
        <a-form-item label="发送对象" name="user_group">
          <a-checkbox-group v-model:value="userGroup" :options="userGroupOptions"/>
        </a-form-item>
      </a-form>
    </a-modal>
  </template>
  
  <!-- 搜索栏 -->
  <a-space size="middle">
    <a-form layout="inline" ref="formRef" name="tags_search" :model="searchForm" @finish="onFinish">
      <a-form-item label="通知标题" name="title">
        <a-input v-model:value="searchForm.title" allow-clear></a-input>
      </a-form-item>
      <a-form-item label="通知状态" name="state">
        <a-select v-model:value="searchForm.state" placeholder="请选择状态" :options="stateOptions"></a-select>
      </a-form-item>
      <a-form-item label="添加时间" name="create_time">
        <a-range-picker style="width: 260px" format="YYYY-MM-DD" :allow-clear="true" :placeholder="['开始时间', '结束时间']" @change="onChangeDatePicker"/>
      </a-form-item>
      <a-button type="primary" html-type="submit">
        <search-outlined/>
        搜索
      </a-button>
    </a-form>
  </a-space>
  
  <!-- 数据展示 -->
  <div style="margin: 10px 0">
    <a-space style="margin-bottom: 10px">
      <a-button type="primary" @click="showModal">
        <PlusOutlined/>
        添加数据
      </a-button>
    </a-space>
    
    <a-table bordered @change="getList" :columns="columns" :data-source="data" :pagination="pagination" :show-sorter-tooltip="true">
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'title'">
          <a>{{ record.title }}</a>
        </template>
        <template v-else-if="column.key === 'state'">
          <a-switch v-model:checked="record.state" checked-children="启用" un-checked-children="禁用" @change="handleChangeState($event, record.id,)"/>
        </template>
        
        <template v-else-if="column.key === 'action'">
          <a-space>
            <a-button type="primary" @click="showModal(record.id)">编辑</a-button>
            <a-popconfirm title="确认删除吗?" @confirm="handleDelete(record.id)" ok-text="确认" cancel-text="删除">
              <a-button type="primary" danger>删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>
  </div>
</template>

<style scoped>

</style>